package vn.demand.dragon.model
{
	import mx.rpc.IResponder;
	
	import org.puremvc.as3.interfaces.IProxy;
	import org.puremvc.as3.patterns.proxy.Proxy;
	
	import vn.demand.dragon.CommonCommand;
	import vn.demand.dragon.model.business.UserLoginDelegate;
	import vn.demand.dragon.model.business.UserLogoutDelegate;
	
	public class UserProxy extends Proxy implements IProxy, IResponder
	{
		public static const NAME:String = "UserProxy";
		
		public var userInfo:Object;
		
		public function UserProxy(proxyId:String = NAME)
		{
			super(proxyId);
		}
		
		public function login(userName:String, password:String):void {
			var delegate:UserLoginDelegate = new UserLoginDelegate(this);
			delegate.login(userName, password);
		}
		
		// this is called when the delegate receives a result from the service
		public function result( rpcEvent : Object ) : void
		{
			var success:Boolean = rpcEvent.result.success == 'true'; 
			if (success) {
				//userInfo = {'user_id': 1, 'username': 'Admin', 'div_id': '1', 'div_name': 'division chua co ten', 'cc_id': '1', 'cc_name': 'costcenter chua co ten'}
				userInfo = rpcEvent.result.user;
				sendNotification(CommonCommand.LOGIN_SUCCESSFUL, userInfo);
			} else {
				errorStatus = rpcEvent.result.errors;
				sendNotification(CommonCommand.LOGIN_FAILED, errorStatus);				
			}
		}
		
		// this is called when the delegate receives a fault from the service
		public function fault( rpcEvent : Object ) : void 
		{
			errorStatus = "Something wrong when login!";
			sendNotification(CommonCommand.LOGIN_FAILED, errorStatus);
		}
		
		public function logout() {
			var delegate:UserLogoutDelegate = new UserLogoutDelegate(
				function(rcpEvent:Object) {
			
				},
				function(rcpEvent:Object) {
			
				});
			delegate.logout();
		}

		[Bindable] public var errorStatus:String = null;
	}
}